<template>
  <div id="discuss">
    <Wangeditor ref="Wangeditor1"
      v-bind="{ menu, height, Toolbarshow, handleFocus, handleBlur, placeholder: '这里可以讨论关于比赛的问题，灌水等行为会被删帖哦！' }">
    </Wangeditor>
    <div class="row">
      <div class="text-right pd col">
        <el-button size="default" type="primary" @click="submit({ pid: null })">发布评论</el-button>
      </div>
    </div>
    <div class="QxT4hD">
      <span class="_2R7vBo">{{ count }}条评论</span>
    </div>
    <el-container class="user border-bottom" :style="{ marginBottom: '24px' }" v-for="(v, key) in getfabulouscomment"
      :key="key">
      <el-aside width="40px" class="imag">
        <router-link v-slot="{ navigate }" custom :to="{
        name: '用户',
        query: { userid: v.userid },
      }">
          <el-avatar @click="navigate" size="default" :src="v.user?.headportrait"></el-avatar>
        </router-link>
      </el-aside>
      <el-main class="context">
        <header class="row">
          <div class="col username">
            <router-link v-slot="{ href }" custom :to="{
        name: '用户',
        query: { userid: v.userid },
      }">
              <el-link :href="href" :style="{ '--el-link-font-weight': 700 }">{{ v.user?.name }}
              </el-link>
            </router-link>
            <el-tag size="small" v-show="tag(v)" class="mx-1" effect="dark" round>
              已参赛
            </el-tag>
          </div>
          <div class="text-right" :style="{ width: '200px' }">
          </div>
          <div class="col-1 text-right" v-if="user?.type === 'admin'">
            <el-popover trigger="click" placement="top" :width="160">
              <div style="text-align: center; margin: 0">
                <el-button size="small" type="primary" @click="handleCommand('a', v.ID, !v.top)">删除</el-button>
                <el-button size="small" @click="handleCommand('b', v.ID, !v.top)">{{ v.top ? "取消置顶" : "置顶" }}
                </el-button>
              </div>
              <template #reference>
                <el-icon class="icon1">
                  <MoreFilled />
                </el-icon>
              </template>
            </el-popover>
          </div>
        </header>
        <div class="text-html">
          <div v-html="v.context" class="editor-content-view"></div>
        </div>
        <div class="text-icon-a">
          <div>
            <span v-text="TimeYH(v.createdAt)"></span>
            <span class="cu" @click="xinxiclick(key)">回复</span>
          </div>
          <el-collapse-transition>
            <div class="input-f" v-show="inputkey === key">
              <el-input :minlength="5" :placeholder="`回复:${v.user?.name}`" v-model="input">
                <template #append>
                  <el-button @click="reply(v.ID, input)">发布</el-button>
                </template>
              </el-input>
            </div>
          </el-collapse-transition>
        </div>
        <el-container class="text" v-for="(item, keys) in v.matchcommenta" :key="`${key}-${keys}`"
          :style="{ marginBottom: '24px' }">
          <el-aside width="55px" class="imag">
            <router-link v-slot="{ navigate }" custom :to="{
        name: '用户',
        query: { userid: item.userid },
      }">
              <el-avatar @click="navigate" size="default" :src="item.user?.headportrait"></el-avatar>
            </router-link>

          </el-aside>
          <el-main class="p-0">
            <header class="row m-0">
              <div class="col p-0 username">
                <router-link v-slot="{ href }" custom :to="{
        name: '用户',
        query: { userid: item.userid },
      }">
                  <el-link :href="href" :style="{ '--el-link-font-weight': 700 }">{{ item.user?.name }}
                  </el-link>
                </router-link>

              </div>
              <div class="col-1 text-right p-0">
              </div>
            </header>
            <div class="text-html editor-content-view" v-html="item.context"></div>
          </el-main>
        </el-container>
      </el-main>
    </el-container>
    <div class="m-p-6 text-right">
      <el-pagination :page-size="limit" :total="count" @current-change="(r) => (offset = limit * (r - 1))"
        layout="prev, pager, next" :current-page="Math.floor(offset / limit) + 1"></el-pagination>
    </div>
  </div>
</template>
<script setup lang="ts">
import { MoreFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElPagination } from "element-plus";
import highlight from 'highlight.js';
import { computed, inject, nextTick, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import {
  asyncchangematchcomment,
  asynccreatematchcomment,
  asyncdelmatchcomment,
  asyncgetmatchcomment
} from "../../../api";
import Wangeditor, { Emenu } from "../../../components/wangeditor.vue";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { flattenpid } from "../../../util/code";
import { TimeYH } from '../../../util/time';

const props = defineProps<{ ID?: number, user?: Studycodemodel.Iuser, activity?: Studycodemodel.Iactivity, activityusers?: Studycodemodel.Iactivityuser[] }>()
const menu: Emenu = [
  "head", // 标题
  "fontSize", // 字号 

  "italic", // 斜体
  "strikeThrough", // 删除线
  "foreColor", // 文字颜色
  "backColor", // 背景颜色
  "link", // 插入链接
  "justify", // 对齐方式
  "quote", // 引用
  "emoticon", // 表情
  "image", // 插入图片
  "code", // 插入代码
  "undo", // 撤销
  "redo", // 重复
]

const fabulouscomment = ref<Studycodemodel.Imatchcomment[]>([])
const input = ref('')
const inputkey = ref<number | null>(null)
const count = ref(0)
const offset = ref(0)
const limit = ref(10)
const height = ref("42px")
const getfabulouscomment = computed(() => {
  return fabulouscomment.value
})

const Toolbarshow = ref(false)
const f = ref(false)
onMounted(() => {
  start()
  setTimeout(() => {
    f.value = true
  }, 1000)
})

watch(() => props.ID, start)
watch(() => offset.value, start)
async function start() {
  try {
    const data = await asyncgetmatchcomment({
      ID: props.ID ? props.ID : 0,
      _limit: limit.value,
      _offset: offset.value,
      _order: ["top", "ID"],
      state: [1, 2]
    });
    count.value = data.count;
    fabulouscomment.value = data.rows;
  } catch (e: any) {
    console.log(e);
  }
  nextTick(() => {
    highlight.highlightAll()
  })
}

async function reply(pid: any, text: string) {
  const ID = props.ID;
  if (text.length < 5) {
    ElMessage.error("评论内容过少");
    return;
  }
  if (!text && !ID) return;
  try {
    await asynccreatematchcomment({
      pid,
      context: text,
      activityid: ID ? ID : 0,
      text: text,
      htmlcontext: "",
    });
    ElMessage.success("评论成功");
    inputkey.value = null;
    input.value = "";
  } catch (e: any) {
    input.value = "";
    ElMessage.error(e);
  }
  start();
}
function flatten({ children = [] }) {
  const data = flattenpid(children);
  return data;
}
const store = useStore(Storekey)

const getuser = computed(() => {
  return store.state.user
})
const loginfunction = inject<(key: string) => void>('headnavdialogVisible')
function xinxiclick(key: number) {
  if (!getuser.value && loginfunction) {
    loginfunction('登录')
    return;
  }
  if (key === inputkey.value) {
    inputkey.value = null;
  } else {
    inputkey.value = key;
  }
}
function findcolor(v?: any[]) {
  if (v) {
    return v.find((v) => v.userid == props.user?.ID)
      ? "icon-tn"
      : "icon-t";
  }
  return "icon-t";
}

const Wangeditor1 = ref()
async function submit({ pid }: any) {
  if (!getuser.value && loginfunction) {
    loginfunction('登录')
    return;
  }
  const editor: any = Wangeditor1.value;
  const html: string = editor.syncHTML();
  const text: string = editor.gettext();
  const htmlcontext: string = editor.getcontext();
  if (text.length < 5) {
    ElMessage.error("评论内容过少");
    return;
  }
  try {
    await asynccreatematchcomment({
      pid,
      context: html,
      activityid: props.ID ? props.ID : 0,
      text: text,
      htmlcontext,
      activityname: props.activity?.name
    });
    ElMessage.success("评论成功，审核通过后可见");
    editor.removeNodes();
  } catch (e: any) {
    ElMessage.error(e);
  }
  start();
}
function handleFocus() {
  if (f.value) {
    height.value = "400px";
    Toolbarshow.value = true
  } else {
    Wangeditor1.value?.instance.blur()
  }
}
function handleBlur() {
  height.value = "42px";
  Toolbarshow.value = false
}
async function handleCommand(n: string, ID?: number, top: boolean = false) {
  if (n === "a") {
    ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "error",
    }).then(async () => {
      try {
        if (ID) {
          await asyncdelmatchcomment({ ID });
          ElMessage.success("删除成功");
          start();
        }
      } catch (e: any) {
        ElMessage.error(e);
      }
    });
  }
  if (n === "b" && ID) {
    await asyncchangematchcomment({ ID, top });
    await start();
  }
}


function tag(row: Studycodemodel.Imatchcomment) {
  const { user = {} } = row
  const k = props.activityusers?.find(e => {
    return user.ID === e.userid
  })
  if (k) {
    return true
  }
  return user.teamuser?.find(e => {
    return e.teamid === props.activity?.teamid
  })
}

</script>

<style scoped>
.pd {
  padding-top: 24px;
  padding-bottom: 24px;
  width: 80px;
}

.QxT4hD {
  margin-bottom: 24px;
  padding-left: 12px;
  font-size: 14px;
  background: #f5f5f5;
  border-radius: 2px;
  height: 48px;
  line-height: 48px;
  color: #000;
}

.icon {
  font-size: 20px;
  color: var(--color-AAAAAA);
}

.cu {
  cursor: pointer;
  display: inline-block;
  margin-right: 26px;
  font-size: 14px;
}

.text-aa {
  color: var(--color-AAAAAA);
}

.context {
  padding-top: 1px;
  padding-bottom: 1px;
  padding-left: 15px;
  padding-right: 15px;
}

.context header {
  color: var(--color-43);
}

.wang {
  height: 165px;
}

.username {
  font-size: 14px;
  color: #8c8c8c;
}

.text-sm-right {
  font-size: 12px;
  color: var(--color-8898AA);
  text-align: right;
}

.input-f {
  margin-top: 3px;
  margin-bottom: 3px;
}

.text-html {
  font-size: 14px;
}

.text-icon-a {
  min-height: 40px;
  font-size: 14px;
  padding-top: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.text-icon-a span {
  display: inline-block;
  margin-right: 26px;
}

.icon1 {
  transform: rotate(90deg);
}

.icon-t:hover {
  color: var(--color-cheng);
}

.icon-tn {
  color: var(--color-cheng);
}

#discuss {
  padding: 15px;
}
</style>

<style>
#discuss p {
  margin-bottom: 0px;
}

#discuss .w-e-text-placeholder {
  top: 8px
}
</style>